package com.adam.management.controller;

import com.adam.management.response.ResponseData;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @projectName: adam-management-system
 * @description:
 * @author: Adam
 * @create: 2019-12-01 18:18
 **/

@Component("UserLoginAuthenticationSuccessHandler")
public class UserLoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private static Logger logger = LoggerFactory.getLogger(UserLoginAuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        logger.info("=====>>>>>登录成功>>>>>authentication=[{}]",JSON.toJSONString(authentication));
        ResponseData<String> responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMessage("认证成功");
        responseData.setData("/index");
        String json = JSON.toJSONString(responseData);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //通过下面配置，登录成功后页面将跳转回引发跳转的页面
        /*private RequestCache requestCache = new HttpSessionRequestCache();
        private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        redirectStrategy.sendRedirect(request, response, savedRequest.getRedirectUrl());*/
        out.write(json);
        out.flush();
        out.close();
    }
}
